<template>
  <div id="conentpage" class="rightBodyContent">
    <div class="rightBodyContent-in">
      <el-button type="primary" plain @click="backlist" size="small" v-if="editId"><i class="el-icon-back"></i>返回列表
      </el-button>
      <el-row class="questionBody">
        <el-col :span="24" class="warp-main">
          <el-form ref="infoForm" :model="infoForm" :rules="rules" label-width="140px">
            <el-form-item label="问卷标题:" prop="title">
              <el-input v-model="infoForm.title" placeholder="问卷标题" v-if="!editId"></el-input>
              <p v-else>{{ infoForm.title }}</p>
            </el-form-item>
            <el-form-item label="问卷描述:" prop="description">
              <quill-editor v-model="infoForm.description"
                            ref="myQuillEditor"
                            class="editer"
                            :options="editorOption" @ready="onEditorReady($event)" placeholder="问卷描述" v-if="!editId">
              </quill-editor>
              <p v-else v-html="infoForm.description?infoForm.description:'无'"></p>
            </el-form-item>
            <el-form-item label="问卷范围:">
              <div v-if="!editId">
                <el-radio-group v-model="teachertype" @change="radiochangeTab">
                  <el-radio :label="0">全校职工</el-radio>
                  <el-radio :label="1">特定职工</el-radio>
                </el-radio-group>
              </div>
              <div v-else>
                <div v-if="infoForm.user_ids">
                  <el-tag
                    :key="index"
                    v-for="(tag,index) in editBody.user_ids"
                    class="mr-10"
                  >{{ tag.realname }}
                  </el-tag>
                </div>
                <div v-else>全校职工</div>
              </div>
            </el-form-item>
            <el-form-item label="选择特定职工:" v-if="teachertype==1">
              <el-button type="primary" @click="chooseStudent" class="mb-10" size="small" plain>选择参与问卷人员</el-button>
              <el-button @click.native="groupVisible=true" size="small">选择执行群组（多选）</el-button>
              <div>
                <el-tag
                  :key="tag.id"
                  v-for="(tag,index) in dynamicTags"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index)"
                  class="mr-10"
                >{{ tag.realname }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="问卷时间:" prop="end_time">
              <div style="display: flex;align-items: center;" v-if="!editId">
                <el-date-picker type="date"
                                class="w-140"
                                placeholder="开始时间"
                                v-model="infoForm.start_time"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
                至
                <el-date-picker type="date"
                                class="w-140"
                                placeholder="结束时间"
                                v-model="infoForm.end_time"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </div>
              <div v-else>
                {{ infoForm.start_time }} 至 {{ infoForm.end_time }}
              </div>
            </el-form-item>
            <el-form-item label="问卷内容:">
              <div class="iconlist questionlist" v-for="(item,i) in infoForm.body" v-if="!editId">
                <div style="display: flex;align-items: center;">
                  <span class="questionIndex">{{ i + 1 }}.</span>
                  <el-input v-model="infoForm.body[i].content" placeholder="填写问卷内容"></el-input>
                  <i class="el-icon-circle-plus-outline iconadd addicon" @click="onAdd(i)"></i>
                  <i class="el-icon-error iconadd detelicon" @click="onDetel(i)"></i>
                </div>
                <div class="questionType">
                  <div>
                    用户问卷回答类型：
                    <el-radio-group v-model="infoForm.body[i].type" @change="radioChange(i)">
                      <el-radio label="1">单选项</el-radio>
                      <el-radio label="2">多选项</el-radio>
                      <el-radio label="3">输入框</el-radio>
                    </el-radio-group>
                    <span class="infoline">(输入框：用户自行输入文字内容)</span>
                  </div>
                  <p>
                    填写类型：
                    <el-radio-group v-model="infoForm.body[i].is_must">
                      <el-radio label="1">必填</el-radio>
                      <el-radio label="0">非必填</el-radio>
                    </el-radio-group>
                  </p>
                </div>
                <!--                  1单 2 多 3输入-->
                <div class="questionline" v-if="infoForm.body[i].type==1||infoForm.body[i].type==2">
                  <div v-for="(item,indexs) in infoForm.body[i].option" class="questionline-list">
                    <p>
                      {{ qustionCheck[indexs] }}.
                      <el-input v-model="infoForm.body[i].option[indexs].text" placeholder="填写选项内容"></el-input>
                      <i class="el-icon-circle-plus-outline iconadd addicon" @click="addlinebox(i)"
                         v-if="infoForm.body[i].option.length<26"></i>
                      <i class="el-icon-error iconadd detelicon" @click="detellinebox(i,indexs)"></i>
                    </p>
                    <div class="questionLine-list">
                      <p>
                        是否添加输入框：
                        <el-radio-group v-model="infoForm.body[i].option[indexs].type">
                          <el-radio label="1">是</el-radio>
                          <el-radio label="2">否</el-radio>
                        </el-radio-group>
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else>
                <el-button @click="gotoExcel()" class="mb-10" size="mini">导出题目内容excel明细</el-button>
                <div v-for="(items,index) in listCheck">
                  {{ index + 1 }}.{{ items.content }}
                  <div v-if="items.type!==3">
                    <div v-for="(line,indexs) in items.option" class="inlinebox">
                      <p>
                        {{ line.index }}.{{ line.text }}
                        <span>({{ line.number }}票)</span>
                        <span v-if="line.type==1">(可输入自定义文字)</span>
                      </p>
                      <p v-if="line.type==1" class="showuserAnswer">
                        用户提交项：
                        <span v-for="useroption in line.content">（{{ useroption }}）</span>
                      </p>
                    </div>
                  </div>
                  <div class="inlinebox" v-else>
                    <p>用户自行填写</p>
                    <p class="showuserAnswer">用户提交项：<span v-for="useroption in items.option">（{{ useroption }}）</span>
                    </p>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit" v-if="!editId" size="small">确认提交</el-button>
              <el-button @click="backlist" v-else size="small">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <!--    <teacherMultiple :visible.sync="studentVisible" @studentFn="studentFn" :userclassId="infoForm.class_id"-->
    <!--                     :usersectionId="infoForm.section_id" :dynamicTagsArray="dynamicTagsArray"></teacherMultiple>-->
    <MultipleTeacherModle :visible.sync="studentVisible" @studentFn="studentFn" :userclassId="infoForm.class_id"
                          :usersectionId="infoForm.section_id"
                          :dynamicTagsArray="dynamicTagsArray"></MultipleTeacherModle>
    <!--    选择群组-->
    <groupModule :visible.sync="groupVisible" @studentFn="studentFn"></groupModule>
  </div>
</template>

<script>
import {yeartime} from '@/assets/js/common'
import classInput from '@/components/template/classInput.vue'
import sectionInput from '@/components/template/sectionInput.vue'
import {pagination} from '@/utils/util.js'

import {quillEditor} from 'vue-quill-editor' // 调用编辑器
import quillConfig from '@/assets/js/quill-config.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  components: {
    quillEditor,
    classInput,
    sectionInput
  },
  data() {
    return {
      groupVisible: false,
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      qustionCheck: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      editorOption: quillConfig,
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      dialogTableVisible: false,
      infoForm: {
        body: [{'content': null, is_must: '1', 'type': '1', 'option': [{text: '', type: '2'}]}],
        title: '',
        start_time: yeartime(new Date()),
        end_time: yeartime(new Date()),
        user_ids: 0,
        description: '' //  描述
      },

      // 表单验证
      rules: {
        title: [
          {required: true, message: '填写问卷标题', trigger: 'blur'}
        ]
      },
      arryList: null,
      usersName: null,
      editId: this.$route.query.editId,
      listCheck: [],
      value1: [],
      sectionList: [],
      classesList: [],
      oldClass: {}, // 未处理的班级
      oldsection: {}, // 未处理的年段
      editClass_id: [],
      editsection_id: [],
      studentVisible: false,
      teachertype: 0,
      dynamicTags: [],
      dynamicTagsArray: {},
      editBody: null
    }
  },
  watch: {
    '$route'(to, from) {
      // 这样就可以获取到变化的参数了，然后执行参数变化后相应的逻辑就行了
      console.log('路由参数变化', this.$route.query, this.$route.query.editId, !this.$route.query.editId)
      if (!this.$route.query.editId) {
        this.editId = ''
      }
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  created() {

  },
  mounted() {
    if (this.editId) {
      this.Inint()
    }
  },
  methods: {
    Inint() {
      this.$fetch(this.api.questionnaire_inside_detail, {id: this.editId}).then((response) => {
        if (response.code === 0) {
          this.infoForm.start_time = response.vo.start_time
          this.infoForm.end_time = response.vo.end_time
          this.infoForm.title = response.vo.title
          this.listCheck = response.list
          this.infoForm.type = response.vo.type
          this.infoForm.class_id = response.vo.class_id
          this.infoForm.description = response.vo.description
          // 0全校 1特定年段 2特定班级
          if (Number(response.vo.type) === 1) {
            this.editsection_id = response.vo.section_id
          } else if (Number(response.vo.type) === 2) {
            this.editClass_id = response.vo.class_id
          }

          this.editBody = response.vo
          this.detailCheckFn()
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    detailCheckFn() {
      console.log('listCheck', this.listCheck)
      for (let i in this.listCheck) {
        let option = this.listCheck[i]
        // type 1 单选项 2 多选项 3 输入框
        this.$fetch(this.api.questionnaire_inside_option, {id: this.listCheck[i].id}).then((response) => {
          if (response.code === 0) {
            for (let j in response.list) {
              // type  1 是 2 否
              if (this.listCheck[i].type !== 3) {
                option.option[j].number = response.list[j].number
                if (Number(option.option[j].type) === 1) {
                  option.option[j].content = response.list[j].content
                }
              } else {
                option.option = response.list[j].content
              }
            }
            this.$set(this.listCheck, i, option)
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      }
    },
    onEditorReady(editor) {
    },
    onAdd(index) {
      this.infoForm.body.splice(index + 1, 0, {'content': null, is_must: '1', 'type': '1', 'option': [{text: '', type: '2'}]})
    },
    addlinebox(i) {
      this.infoForm.body[i].option.push({text: '', type: '2'})
    },
    detellinebox(i, index) {
      this.infoForm.body[i].option.splice(index, 1)
      if (!this.infoForm.body[i].option.length) {
        this.addlinebox(i)
      }
    },
    onDetel(index) {
      this.infoForm.body.splice(index, 1)
      if (!this.infoForm.body.length) {
        this.infoForm.body.push({
          'content': null,
          'type': '1',
          is_must: '1',
          'option': [{text: '', type: '2', is_commitment: '0'}]
        })
      }
    },
    // 设置默认选中
    checked() {
      console.log('默认选项判断', this.applyBookBox)
      for (let i = 0; i < this.arryList.length; i++) {
        if (this.applyBookBox[this.arryList[i].id]) {
          console.log('数值', i)
          this.$refs.table.toggleRowSelection(this.arryList[i], true)
        }
      }
    },
    radioChange(e) {
      if (this.infoForm.body[e].type == 3) {
        this.infoForm.body[e].option = []
      } else {
        this.infoForm.body[e].option = [{text: '', type: '2'}]
      }
    },
    backlist() {
      this.$router.go(-1)
    },
    radiochangeTab() {
      0
      this.infoForm.user_ids = 0
    },
    onSubmit() {
      // 提交 this.$refs.infoForm.validate，这是表单验证
      console.log('数据提交', this.infoForm, this.value1)
      if (!this.infoForm.title) {
        this.$message({
          message: '请填写问卷标题',
          type: 'error'
        })
        return
      }
      // 1单 2 多 3输入
      for (let i in this.infoForm.body) {
        if (!this.infoForm.body[i].content) {
          this.$message({
            message: '请填写问卷内容',
            type: 'error'
          })
          return
        }
        if (this.infoForm.body[i].type == 1 || this.infoForm.body[i].type == 2) {
          for (let j in this.infoForm.body[i].option) {
            if (!this.infoForm.body[i].option[j].text) {
              console.log('none')
              this.$message({
                message: '请填写问卷选项',
                type: 'error'
              })
              return
            }
          }
        }
      }
      if (this.teachertype === 1 && !this.dynamicTags.length) {
        this.$message({
          message: '请选择特定职工',
          type: 'error'
        })
        return
      }
      let data_ = {}
      let body_ = this.infoForm.body
      for (let i in body_) {
        if (body_[i].type !== 3) {
          for (let j in body_[i].option) {
            body_[i].option[j]['index'] = this.qustionCheck[j]
          }
        }
      }
      let users = []
      for (let item of this.dynamicTags) {
        users.push(item.id)
      }
      data_.title = this.infoForm.title
      data_.start_time = this.infoForm.start_time
      data_.end_time = this.infoForm.end_time
      data_.body = JSON.stringify(body_)
      data_.user_ids = users.join(',')
      data_.description = this.infoForm.description
      console.log(data_)
      // let data_option = 1
      // if(data_option){
      //   return
      // }
      this.$refs['infoForm'].validate((valid) => {
        console.log('状态：', valid)
        if (valid) {
          this.$post(this.api.questionnaire_inside_add, data_).then(res => {
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.infoForm = {
                body: [{'content': null, is_must: '1', 'type': '1', 'option': [{text: '', type: '2'}]}],
                // body: [{'title': null, 'type': '1', is_must: '1', 'content': ['']}],
                title: '',
                class_id: '',
                section_id: '',
                start_time: yeartime(new Date()),
                end_time: yeartime(new Date()),
                student_id: 0
              }
              this.teachertype = 0
              this.dynamicTags = []
              this.dynamicTagsId = []
              this.dynamicTagsArray = {}
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          })
        }
      })
    },
    chooseStudent() {
      let list = {}
      for (let item of this.dynamicTags) {
        list[item.id] = item
      }
      this.dynamicTagsArray = this.getJson(list)
      this.studentVisible = true
    },
    handleClose(index) {
      this.dynamicTags.splice(index, 1)
    },
    studentFn(option) {
      let list = [];
      for (let i in option) {
        list.push(option[i])
      }
      this.dynamicTags = this.getJson(list)
    },
    gotoExcel(index) {
      this.$http({
        method: 'get',
        url: `${this.$BASE_URL}/admin/` + this.api.inside.export_index + '?id=' + this.editId,
        responseType: 'arraybuffer'
      })
        .then(
          function (response) {
            this.fileDownload(response.data, this.infoForm.title)
          }.bind(this)
        )
        .catch(
          function (error) {
            alert('网络请求出错')
          }
        )
    },
    gotoExcelOnly(line, id, title) {
      console.log('内容信息：', line, id, title)
      this.$http({
        method: 'get',
        url: `${this.$BASE_URL}/admin/` + this.api.inside.sign_export + '?question_id=' + id + '&option=' + line.index,
        responseType: 'arraybuffer'
      })
        .then(
          function (response) {
            this.fileDownload(response.data, title + ',' + line.index + '.' + line.text)
          }.bind(this)
        )
        .catch(
          function (error) {
            alert('网络请求出错')
          }
        )
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option))
    },
    fileDownload(data, pushname) {
      let blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      let filename = pushname + '-填写明细.xls' || 'filename.xls'
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        let blobURL = window.URL.createObjectURL(blob)
        let tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    }
  }
}
</script>
<style lang="scss">

.questionlist:last-child .questionlist {
  border-bottom: 0;
}

.inlinebox {
  padding-left: 20px;
}

.infoline {
  font-size: 12px;
  color: #777;
  margin-left: 10px;
}

.ql-editor {
  max-height: 250px;
}

.el-dialog__body {
  padding: 0 20px;
}

.el-radio__label {
  /*display: none;*/
}

.warp {
  width: 80%;
  padding: 30px;
  margin: 0 auto;
}

.el-dialog__body {
  /*text-align: center;*/
}

.el-pagination {
  padding-top: 20px;
}


.iconadd {
  cursor: pointer;
  font-size: 20px;
  margin-left: 10px;
}

.iconlist {
  margin-bottom: 10px;
}

.addicon {

}

.detelicon {
  color: red;
}
</style>
